//app.js
const http = require("./utils/http")
const wxToast = require("./utils/wx-toast")
const toPromise = require("./utils/to-promise")
const cartData = new Map()
import md5 from './utils/md5.js'
const tabs = [{
        name: "全部",
        status: null
    },
    {
        name: "待付款",
        status: 0
    },
    {
        name: "待配送",
        status: 20
    },
    {
        name: "已发货",
        status: 21
    },
    {
        name: "待自提",
        status: 11
    },
    {
        name: "已完成",
        status: 40
    },
    {
        name: "已取消",
        status: -1
    },
]
const write_off_tab = [{
        name: "全部",
        status: null
    },
    {
        name: "待付款",
        status: 0
    },
    {
        name: "已支付",
        status: 12
    },
    {
        name: "已完成",
        status: 100
    },
]
App({
    onLaunch: function() {
        const updateManager = wx.getUpdateManager()
        updateManager.onCheckForUpdate(res => {
            // 请求完新版本信息的回调
            console.log(res.hasUpdate)
        })

        updateManager.onUpdateReady(() => {
            wx.showModal({
                title: '更新提示',
                content: '新版本已经准备好，是否重启应用？',
                confirmColor: '#ff5400',
                success: res => {
                    if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate()
                    }
                }
            })
        })

        updateManager.onUpdateFailed(function() {
            // 新版本下载失败
        })
        wx.getSystemInfo({
            success: res => {
                this.scrollWidth = res.windowWidth
            }
        });
    },
    http,
    tabs,
    write_off_tab,
    wxToast,
    toPromise,
    cartData,
    onPageNotFound(res) {
        wx.switchTab({
            url: 'pages/index/index',
        })
    },

    /** 
     *  数组对象按key升序, 并生成 md5_hex 签名
     * @param {Array/Object} obj   数组对象
     * @return {String}  encrypted md5加密后的字符串
     */
    makeSign: function(obj) {
        if (!obj) {
            console.log('需要加密的数组对象为空')
        }
        var str = '';
        var secret = this.gdConfig.appSecret;
        if (!secret) {
            console.log('密钥未获取');
        }
        //生成key升序数组
        var arr = Object.keys(obj);

        arr.sort();
        for (var i in arr) {
            if (obj[arr[i]] && arr[i] != 'sign') {
                str += arr[i] + '=' + obj[arr[i]] + '&';
            }
        }
        str = str.substring(0, str.length - 1)
        var encrypted = md5(str + secret);
        return encrypted;
    },
    //高德key  签名密钥
    gdConfig: {
        key: "405b13b07a486ebd903ba535faefa811",
        appSecret: 'llsqtgjm',
    },
    isGetPhone() {
        return new Promise((resolve, reject) => {
            this.http.post('authorize/isset-mobile').then(res => {
                resolve(res.data)
            }).catch(err => {
                reject()
            })
        })
    },
    getThisPage() {
        let ps = getCurrentPages()
        return ps[ps.length - 1]
    },
    getShareObj(title = "", params = {}, imageUrl = '') {
        const id = wx.getStorageSync('mid')
        if (!id) {
            return {}
        }
        const paramsArr = ["pmid=" + id]
        Object.keys(params).forEach(k => {
            paramsArr.push(k + "=" + params[k])
        })
        const ps = getCurrentPages()
        console.log(title, "/" + ps[ps.length - 1].route + "?" + paramsArr.join("&"))
        return {
            title,
            path: "/" + ps[ps.length - 1].route + "?" + paramsArr.join("&"),
            imageUrl
        }
    },
    share(mid) {
        if (!mid) return
        let data = {
            mid,
        }
        data.sign = this.makeSign(data)
        this.http.get('distributor/join', {
            data
        })
    },
    loadCart() {
        http.get('shopping-cart/quantity', {
            data: {
                id: wx.getStorageSync('cid')
            },
        }).then(res => {
            this.getThisPage().setData({
                cartNum: parseInt(res.data)
            })
            this.setTabCart(parseInt(res.data))
        })
    },
    setTabCart(cartNum) {
        if (cartNum == 0) {
            wx.removeTabBarBadge({
                index: 3,
            })
            return
        }
        wx.setTabBarBadge({
            index: 3,
            text: cartNum + ''
        })
    },
    community() {
        const ps = getCurrentPages()
        let current = ps[ps.length - 1]
        http.get('administrator/community-list').then(res => {
            current.setData({
                communityList: res.data
            })
        })
    },
    //加入购物车
    addToCart(params = {}) {
        return new Promise((resolve, reject) => {
            params['cid'] = wx.getStorageSync('cid')
            http.post("shopping-cart/add", {
                data: params
            }).then(res => {
                if (res.data.status != 1) {
                    wx.showModal({
                        title: '提示',
                        content: res.data.msg,
                        showCancel: false,
                        confirmColor: '#ff5400'
                    })
                    reject()
                }
                this.loadCart()
                resolve(res.data.data)
            })
        })
    },
})